﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TicTacToe : MonoBehaviour
{
    private int[,] board = new int[3, 3];
    private int turn;
    private int num;

    //Reset board
    void restart()
    {
        turn = 1;
        num = 0;
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                board[i, j] = 0;
            }
        }
    }

    //Judge the result of the game
    private int judge()
    {
        for(int i = 0; i < 3; i++)
        {
            if (board[i, 0] == board[i, 1] && board[i, 1] == board[i, 2])
                return board[i, 0];
            if (board[0, i] == board[1, i] && board[1, i] == board[2, i])
                return board[0, i];
        }

        if (board[0, 0] == board[1, 1] && board[1, 1] == board[2, 2])
            return board[1, 1];
        if (board[2, 0] == board[1, 1] && board[1, 1] == board[0, 2])
            return board[1, 1];

        if (num == 9)
            return 3;

        return 0;
    }
    
    void Start()
    {
        restart();
    }

    void OnGUI()
    {
        GUI.skin.button.fontSize =20;
        GUI.skin.label.fontSize = 30;

        if (GUI.Button(new Rect(Screen.width / 2 - 150, 350, 300, 100), "Reset"))
        {
            restart();
        }

        int res = judge();
        if (res == 1)
        {
            GUI.Label(new Rect(Screen.width / 2 - 50, 0, 300, 100), "O wins");
        }
        else if (res == 2)
        {
            GUI.Label(new Rect(Screen.width / 2 - 50, 0, 300, 100), "X wins");
        }
        else if (res == 3)
        {
            GUI.Label(new Rect(Screen.width / 2 - 50, 0, 300, 100), "Draw");
        }

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (board[i, j] == 1)
                {
                    GUI.Button(new Rect(Screen.width / 2 - 150 + 100 * i, 50 + j * 100, 100, 100), "O");
                }
                else if (board[i, j] == 2)
                {
                    GUI.Button(new Rect(Screen.width / 2 - 150 + 100 * i, 50 + j * 100, 100, 100), "X");
                }

                if (GUI.Button(new Rect(Screen.width / 2 - 150 + 100 * i, 50 + j * 100, 100, 100), ""))
                {
                    if (res == 0)
                    {
                        if (turn % 2 == 1)
                        {
                            board[i, j] = 1;
                        }
                        else
                        {
                            board[i, j] = 2;
                        }
                        turn++;
                        num++;
                    }
                }
            }
        }
    }
}
